package ma.android.oook;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ListLabels extends Activity implements OnClickListener{

	private OookDbAdapter mDbHelper;
	private Cursor labels;
	int [] selectedTagsCodes;
	String [] selectedTagsNames; 

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getString(R.string.labels));
		setContentView(R.layout.listlabels);

		mDbHelper = new OookDbAdapter(this);

		mDbHelper.open();
		labels = mDbHelper.findTags();
		startManagingCursor(labels);
		ListView listView = (ListView) findViewById(R.id.labelList);

		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setAdapter(new SimpleCursorAdapter(this,R.layout.multiplechoiceitem,
				labels,new String []{"description"},new int []{android.R.id.text1 }));

		Button accept = (Button) findViewById(R.id.acceptLabel);
		accept.setOnClickListener(this);
		Button newTag = (Button) findViewById(R.id.creatNewLabel);
		newTag.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		ListView list = (ListView) findViewById(R.id.labelList);
		SparseBooleanArray checked = list.getCheckedItemPositions();
		Intent intent;
		switch (v.getId())
		{
			case R.id.acceptLabel:	int [] selectedTagsCodes= new int[checked.size()];
									String [] selectedTagsNames = new String[checked.size()];
									labels = mDbHelper.findTags();
									startManagingCursor(labels);
									for (int i =0;i<checked.size();i++)
									{
										labels.moveToPosition(checked.keyAt(i));
										selectedTagsCodes[i] = labels.getInt(0);
										selectedTagsNames[i]= labels.getString(2);
									}
									labels.close();
									mDbHelper.close();
									intent = getIntent();
									intent.putExtra(getString(R.string.selectedTagsCodes), selectedTagsCodes);
									intent.putExtra(getString(R.string.selectedTagsNames), selectedTagsNames);
									setResult(2, intent);
									finish();								
									break;

		case R.id.creatNewLabel:	intent = new Intent(this,NewLabel.class);
									startActivityForResult(intent, 1);
									break;
		}
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{ 
		if (requestCode == resultCode )
		{
			setResult(3, getIntent());
			finish();
		}
	}
	
}	
